package com.eascs.dubbo.api.crm;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.customer.CustomerApiService;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.form.PayMentForm;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.dao.O2oLoanUserDao;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.form.LoanUserForm;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.dao.O2oZxDao;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.trans.O2oUserZxTransFormart;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.admin.o2o.zx.entity.O2oZxSulpmentEntity;
import com.eascs.admin.o2o.zx.entity.O2oZxSulpmentRecordLogEntity;
import com.eascs.admin.o2o.zx.from.AddO2oZxForm;
import com.eascs.admin.o2o.zx.service.IO2oLoanUserService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.exception.WarnAssertionException;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.nsEditDetail.entity.CustomerAssetInfo;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.crm.nsEditDetail.vo.LoanBaseInfoVO;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.dubbo.api.util.UserUtils;
import com.eascs.notify.sms.SmsNotifier;
import com.eascs.notify.sms.SmsNotifyRequest;
import com.eascs.notify.sms.SmsNotifyResponse;
import com.eascs.notify.sms.SmsSendType;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;

/**
 * 客户dubbo服务化----提供APP业务支撑
 * 
 * @author ycz
 *
 */
@Service
public class CustomerApiServiceImpl implements CustomerApiService {

	private static final Logger logger = LoggerFactory.getLogger(CustomerApiServiceImpl.class);
	@Value("${o2o.admin.wf.NewZxUrl}")
	private String NewZxUrl;

	@Reference
	SysPermissionService sysPermissionService;

	@Reference
	private SmsNotifier smsNotifier;

	@Reference
	private WorkFlowService workFlowService;

	@Autowired
	CustomerAssetInfoService customerAssetInfoService;

	@Autowired
	private O2oDataListService o2oDataListService;

	@Autowired
	O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;

	@Autowired
	O2oPubDdItemService o2oPubDdItemService;

	@Autowired
	CustomerInfoService customerInfoService;

	@Reference
	ICustomerInfoService iCustomerInfoService;

	@Autowired
	O2oLoanUserService o2oLoanUserService;

	@Autowired
	CustomerShopInfoService customerShopInfoService;

	@Reference
	CustomerService customerService;

	@Reference
	SysOrgService sysOrgService;

	@Autowired
	BaseUserUtil userUtils;
	@Autowired
	IO2oLoanUserService iO2oLoanUserService;

	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;

	@Autowired
	O2oZxDao o2oZxDao;

	@Autowired
	O2oLoanUserDao loanDao;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;

	/**
	 * 查询客户资产基本信息
	 * 
	 * @param loanapplyno
	 * @return
	 */
	@Override
	public CustomerAssetInfo queryAssetByLoanapplyNo(String loanapplyno) {
		return customerAssetInfoService.queryById(loanapplyno);
	}

	/**
	 * 夫妻双方的贷款记录
	 */
	@Override
	public PageResult<Object[]> querySpouseLoan(LoanBaseInfoVO vo) {
		return customerInfoService.findCustomerOrMateLoan(vo);
	}

	/**
	 * 夫妻双方担保贷款信息
	 */
	@Override
	public PageResult<Object[]> querySponsorLoanapply(LoanUserForm loanUserForm) {
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(loanUserForm.getUserId());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		if (basicEntity != null && basicEntity.getMateId() != null) {// 配偶id
			String userIds = "'" + loanUserForm.getUserId() + "','" + basicEntity.getMateId() + "'";
			loanUserForm.setUserId(userIds);
		} else {
			loanUserForm.setUserId("'" + loanUserForm.getUserId() + "'");
		}
		return o2oLoanUserService.findSponsorLoanapply(loanUserForm);
	}

	/**
	 * 门店信息
	 */
	@Override
	public PageResult<Object[]> queryCustomerShopInfoList(String loanapplyNo) {
		return customerShopInfoService.page(loanapplyNo);
	}

	/**
	 * 查询客户门店详情
	 * 
	 * @param customerShopId
	 * @return
	 */
	@Override
	public CustomerShopInfoEntity getCustomerShopDetails(String customerShopId) {
		return customerShopInfoService.queryById(customerShopId);
	}

	/**
	 * 保存贷款单
	 */
	@Override
	public void addO2oLoan(AddO2oZxForm addO2oZxForm) {
		CustomerEntity customer = customerService.queryCustomerEntityByCustomerId(addO2oZxForm.getCustomerId());
		if (customer == null) {
			throw new WarnAssertionException("crm中找不到该客户信息，请核实后在申请。");
		}
		ActOrgEntity actOrgEntity = null;
		actOrgEntity = sysOrgService.getOrgByUnitNo(addO2oZxForm.getLtd());
		O2oZxEntity o2oZxEntity = new O2oZxEntity();
		o2oZxEntity.setCreateId(userUtils.getUser().getNo());
		o2oZxEntity.setCreateDate(new Date());
		o2oZxEntity.setCreateName(userUtils.getUser().getCname());
		o2oZxEntity.setIsDel(StatusContexts.O2O_NO);
		o2oZxEntity.setLtd(addO2oZxForm.getLtd());
		o2oZxEntity.setZxStatus(StatusContexts.O2O_NEW);
		o2oZxEntity.setLtdName(actOrgEntity.getOrgName());
		o2oZxEntity.setLtdCode(actOrgEntity.getUnitCode());
		o2oZxEntity.setOperatorId(addO2oZxForm.getOperatorNo());
		o2oZxEntity.setOperatorName(addO2oZxForm.getOperatorName());
		o2oZxEntity.setZxBank(addO2oZxForm.getZxBank());
		o2oZxEntity.setZxType(addO2oZxForm.getZxType());
		o2oZxEntity.setBillCode(o2oZxServiceImpl.buildCode("O2OZX"));
		O2oLoanUserEntityZx o2oLoanUserEntityZx = O2oUserZxTransFormart.customerNewToloanUser(new O2oLoanUserEntityZx(),
				customer, o2oZxEntity.getId());
		o2oZxServiceImpl.saveEntityById(o2oZxEntity, o2oLoanUserEntityZx);
	}

	/**
	 * 夫妻双方征信报告
	 */
	@Override
	public PageResult<Object[]> queryFqZxbg(String loanapplyNo) {

		return o2oZxDao.queryFqZxbg(loanapplyNo);
	}

	/**
	 * 选择征信报告
	 */
	@Override
	public PageResult<Object[]> chooseFqZxbg(String IdNum) {
		return o2oZxDao.loanFqZxbg(IdNum);
	}

	/**
	 * 保存选中的征信报告
	 */
	@Override
	public void saveZxbg(String zxNo, String loanpplyNo) {
		User user = UserHolder.getUser();
		O2oLoanUserEntityZx zxUser = iO2oLoanUserService.getEntityById(zxNo);
		O2oLoanUserEntity loanEntity = o2oLoanUserService.findById(zxUser.getLoanId(), loanpplyNo);
		loanEntity.setZxNo(zxUser.getZxNo());
		loanEntity.setRelationDate(new Date());
		loanEntity.setRelationId(user.getNo());
		loanEntity.setRelationName(user.getCname());
		loanDao.updateById(loanEntity);

		// 2.启动征信报告流程
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(zxUser.getZxNo());
		if ("NEW".equals(o2oZxEntity.getZxStatus())) {
			PayMentForm payform = new PayMentForm();
			String mateId = null;
			payform.setLoanapplyNo(zxUser.getZxNo());
			if (o2oZxEntity.getZxType().equals("ZX_JKR")) {
				mateId = o2oLoanUserService.findMateUserEntity(loanpplyNo);
			} else if (o2oZxEntity.getZxType().equals("ZX_PO")) {
				mateId = loanEntity.getSpouseId();
			}
			if (StringUtils.isNotEmpty(mateId)) {
				payform.setMaterId(mateId);
			}
			boolean flag = checkZxbgstartup(payform);
			boolean isOk = true;
			if (flag) {
				isOk = zxbgstartup(payform);
			}
			if (!flag || !isOk) {
				sendMessage(payform);
			}
		}
	}

	/**
	 * @Title: checkZxbgstartup
	 * @Description:校验是否能够启动征信报告流程
	 * @author 张庆奇
	 * @param payform
	 * @return
	 * @return boolean
	 * @throws @date
	 *             2017年10月18日 上午10:25:57
	 */
	private boolean checkZxbgstartup(PayMentForm payform) {
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(payform.getLoanapplyNo());
		if (!o2oDataListService.checkDataCode(o2oZxEntity.getId(), null)) {
			return false;
		}

		if (StringUtils.isEmpty(o2oZxEntity.getZxBank())) {
			return false;
		}
		return true;
	}

	/**
	 * @Title: zxbgstartup
	 * @Description:启动征信报告流程
	 * @author 张庆奇
	 * @param payform
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年10月17日 下午4:19:01
	 */
	private boolean zxbgstartup(PayMentForm payform) {
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oZxEntity);
		O2oLoanUserEntityZx  o2oLoanUserEntityZx=o2oLoadUserZxServiceImpl.getEntityByZxNo(payform.getLoanapplyNo());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oZxEntity.getId());
		param.setReferCode(o2oZxEntity.getBillCode());
		param.setReferUrl(NewZxUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(StatusContexts.WF_TYPE_CREDIT_INQUIRY);
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(o2oZxEntity.getCreateId());
		param.setAppliedbyName(o2oZxEntity.getCreateName());
		param.setOrgNo(o2oZxEntity.getLtd());
		//param.setReferUrl(backfeeUrl + "?billCode=" + o2oZxEntity.getId()+"&type=1");
		StringBuffer appliedDes = new StringBuffer("姓名:");
		appliedDes.append(o2oLoanUserEntityZx.getUserFullName());
		appliedDes.append("，客户类型:"+o2oPubDdItemService.findPubdditemO2ONameByCode("ZX_TYPE", o2oZxEntity.getZxType()));
		appliedDes.append("，征信银行:"+o2oPubDdItemService.findPubdditemNameByCodeisall("BANKTYPEO2O", o2oZxEntity.getZxBank()));
		param.setAppliedDes(appliedDes.toString());
		param.setLoginUser(UserUtils.getUser(user));
		logger.info("提交征信，参数有征信id：【{}】，征信编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oZxEntity.getId(),o2oZxEntity.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),o2oZxEntity.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			o2oZxEntity.setZxStatus(StatusContexts.WFTYPE_STATUS_RUN);
			o2oZxEntity.setSubmitId(user.getNo());
			o2oZxEntity.setSubmitName(user.getCname());
			o2oZxEntity.setSubmitDate(new Date());
			o2oZxServiceImpl.update(o2oZxEntity);
		} else {
		
			
			logger.error("提交征信流程失败，错误信息{}", modelResult.getDetailStack());
			return false;
		}
		return true;

	}

	private void sendMessage(PayMentForm payform) {
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oZxEntity);
		O2oLoanUserEntityZx  o2oLoanUserEntityZx=o2oLoadUserZxServiceImpl.getEntityByZxNo(payform.getLoanapplyNo());
		User user = UserHolder.getUser();
		//3.失败发送短信
		 ModelResult<User> result = sysPermissionService.getSysUserById(o2oZxEntity.getOperatorId());//信贷经理id
		 User operator  = result.getModel();
		SmsNotifyRequest  smsCustomerRequest=new SmsNotifyRequest();
		smsCustomerRequest.setRequestId(o2oZxEntity.getId());
		smsCustomerRequest.setBizCode(o2oZxEntity.getBillCode());
		smsCustomerRequest.setContent("["+o2oLoanUserEntityZx.getUserFullName()+"]的征信查询流程自动启动失败，请人工发起征信查询流程。");
		smsCustomerRequest.setRecipientNumber(operator.getMobile());
		smsCustomerRequest.setRequestDateTime(new Date());
		smsCustomerRequest.setSmsSendType(SmsSendType.INSTANT);
		smsCustomerRequest.setSystemCode("业务系统");
		smsCustomerRequest.setReceiveName(user.getCname());
		smsCustomerRequest.setSendName("系统");
		try {
			logger.info("征信报告编号：[{}],发送信贷经理手机号:[{}]", o2oZxEntity.getBillCode(),operator.getMobile());
			com.eascs.notify.constant.ModelResult<SmsNotifyResponse> response=smsNotifier.notify(smsCustomerRequest);
			if(!response.isSuccess()){
				
				logger.info("征信报告编号：[{}],发送信贷经理短信发送失败原因:{}", o2oZxEntity.getBillCode(),response.getErrMsg());
			}
		} catch (Exception e) {
			logger.error("征信报告编号：[{}],发送信贷经理短信发送异常:{}",o2oZxEntity.getBillCode(), e.getMessage());
			
		}
	}

	/**
	 * 根据LoanId LoanapplyNo 查借款人征信
	 */
	@Override
	public O2oLoanUserEntity findById(String id, String loanapplyNo) {
		return loanDao.queryLoanpplyNo(loanapplyNo, id);
	}

	/**
	 * 根据LoanId LoanapplyNo 查配偶征信
	 */
	@Override
	public O2oLoanUserEntity findSpouseId(String loanId, String loanapplyNo) {
		return loanDao.findSpouseId(loanId, loanapplyNo);
	}

	/**
	 * 查询附件列表
	 */
	@Override
	public PageResult<Object[]> querDetailList(String id) {
		return o2oLoanapplyService.findO2oDataListEntityById(id);
	}

	/**
	 * 根据LoanId查客户信息
	 */
	@Override
	public O2oLoanUserEntity queryLoanUserById(String loanId) {
		return loanDao.queryLoanUserInfo(loanId);
	}

	@Override
	public PageResult<Object[]> queryBCFqZxbg(String loanapplyNo) {
		return o2oZxDao.queryFqZxbgNew(loanapplyNo);
	}

	@Override
	public PageResult<Object[]> loanFqZxbgNew(String IdNum, String bankLoanName) {
		return o2oZxDao.loanFqZxbgNew(IdNum, bankLoanName);
	}

	@Override
	public int saveBCBG(String loanapplyNo, String id) {
		int i=0;
		User user = UserHolder.getUser();
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(id);
		O2oZxSulpmentEntity o2oZxSulpmentEntity = o2oZxServiceImpl.getZxEntityByZxId(o2oZxEntity.getId());
		if (null == o2oZxSulpmentEntity) {
			o2oZxSulpmentEntity = new O2oZxSulpmentEntity();
			o2oZxSulpmentEntity.setIsDelete(StatusContexts.O2O_NO);
			o2oZxSulpmentEntity.setLoanapplyNo(loanapplyNo);
			o2oZxSulpmentEntity.setZxNo(o2oZxEntity.getId());
			o2oZxSulpmentEntity.setRelationDate(new Date());
			o2oZxSulpmentEntity.setRelationId(user.getNo());
			o2oZxSulpmentEntity.setRelationName(user.getCname());
		    i = o2oZxServiceImpl.insert(o2oZxSulpmentEntity);
			if (i > 0) {
				O2oZxSulpmentRecordLogEntity entity = new O2oZxSulpmentRecordLogEntity();
				entity.setAction("关联征信报告");
				entity.setLoanapplyNo(o2oZxSulpmentEntity.getLoanapplyNo());
				entity.setBillCode(o2oZxEntity.getBillCode());
				entity.setOperationTime(new Date());
				entity.setZxNo(o2oZxSulpmentEntity.getZxNo());
				entity.setUpdateNo(user.getNo());
				entity.setUpdateName(user.getCname());
				i=i+o2oZxServiceImpl.insert(entity);
			}
		}
		return i;
		
	}

	@Override
	public int delBCBG(String id) {
		O2oZxSulpmentEntity zxSulpmentEntity = o2oZxServiceImpl.getZxEntityById(id);
		zxSulpmentEntity.setIsDelete(StatusContexts.O2O_YES);
		int i = o2oZxServiceImpl.update(zxSulpmentEntity);
		if (i > 0) {
			O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(zxSulpmentEntity.getZxNo());
			O2oZxSulpmentRecordLogEntity entity = new O2oZxSulpmentRecordLogEntity();
			entity.setAction("删除征信报告");
			entity.setLoanapplyNo(zxSulpmentEntity.getLoanapplyNo());
			entity.setBillCode(o2oZxEntity.getBillCode());
			entity.setOperationTime(new Date());
			entity.setZxNo(zxSulpmentEntity.getZxNo());
			User user = UserHolder.getUser();
			entity.setUpdateNo(user.getNo());
			entity.setUpdateName(user.getCname());
			i=i+o2oZxServiceImpl.insert(entity);
	        
		}
		return i;
	}
}
